import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useLoadingStore, userTokenStore } from '@/stores'
import router from '@/router'

export const baseURL = 'http://127.0.0.1:8090'
const _axios = axios.create({
	baseURL
})
export const request = (url, method, params, callback) => {
	const loadingStore = useLoadingStore()
	const tokenStore = userTokenStore()
	const axios_config = {
		url,
		method
	}
	if (tokenStore.getToken()) {
		axios_config.headers = {
			'token': tokenStore.getToken()
		}
	}
	if (method === 'post') {
		const formData = new FormData()
		for (const key in params) {
			if (params[key] instanceof Array) {
				for (const i in params[key]) {
					formData.append(key, params[key][i])
				}
			} else {
				formData.append(key, params[key])
			}
		}
		axios_config.data = formData
	} else {
		axios_config.params = params
	}
	loadingStore.openLoading()
	_axios.request(axios_config).then(response => {
		if (response.data.code === 200) {
			if (response.data.message) {
				ElMessage.success(response.data.message)
			}
			callback(response.data.content)
		} else {
			ElMessage.error(response.data.message)
			if (response.data.code === 401) {
				tokenStore.setToken(null)
				router.push('/login')
			}
		}
	}).catch(error => {
		console.dir(error)
		ElMessage.error('网络异常')
	}).finally(() => {
		loadingStore.closeLoading()
	})
}
export const get = (url, params, callback) => { request(url, 'get', params, callback) }
export const post = (url, params, callback) => { request(url, 'post', params, callback) }